package com.zhhs.project.act.appactivity.controller;


import com.zhhs.common.utils.DateUtils;
import com.zhhs.common.utils.StringUtils;
import com.zhhs.framework.web.controller.BaseController;
import com.zhhs.framework.web.domain.AjaxResult;
import com.zhhs.project.act.activity.domian.*;
import com.zhhs.project.act.activity.service.*;
import com.zhhs.project.act.appactivity.common.AppConstants;
import com.zhhs.project.act.appactivity.domian.AppActivityWayVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @description: 抽奖功能接口
 * @author: JiaLe
 * @date: 2022-11-18 09:31
 **/
@Slf4j
@Controller
@RequestMapping("/wecom/mini-app")
public class AppActivityDrawController extends BaseController {
    @Autowired
    private IActDrawService actDrawService;
    @Autowired
    private IActActivityAwardWayService actActivityAwardWayService;
    @Autowired
    private IActActivityUserService actActivityUserService;
    @Autowired
    private IActActivityService actActivityService;
    @Autowired
    private IActActivityBasicsService actActivityBasicsService;
    @Autowired
    private IActUserService actUserService;
    private Lock lock = new ReentrantLock();
    /**
     * 获得当前用户的奖项
     * @param actUserId  参与用户ID
     * @param activityId  活动Id
     * @return
     */
    @PostMapping("/getDrawType")
    @ResponseBody
    public AjaxResult getDrawType(Long actUserId, Long activityId){
        log.info("actUserId:{}",actUserId);
        log.info("activityId:{}",activityId);
        if (actUserId == null){
            return AjaxResult.error(AppConstants.ERROR_CODE_06,"");
        }
        if (activityId == null){
            return AjaxResult.error(AppConstants.ERROR_CODE_06,"");
        }
        ActActivityAwardWay actActivityAwardWay = actActivityAwardWayService.selectActActivityAwardWayByActivityId(activityId);
        log.info("actActivityAwardWay:{}",actActivityAwardWay);
        if (actActivityAwardWay == null){
            return AjaxResult.error(AppConstants.ERROR_CODE_01,"该活动已结束！");
        }

        ActActivity actActivity = actActivityService.selectActActivityById(activityId);
        log.info("actActivity:{}",actActivity);
        if (actActivity == null){
            return AjaxResult.error(AppConstants.ERROR_CODE_01,"该活动已结束！");
        }
        if (AppConstants.ACT_STATUS_01.equals(actActivity.getStatus())){
            return AjaxResult.error(AppConstants.ERROR_CODE_04,"该活动尚未发布！");
        }



        if (AppConstants.ACT_STATUS_02.equals(actActivity.getStatus())){
            return AjaxResult.error(AppConstants.ERROR_CODE_05,"该活动尚未开始！");
        }
        if (AppConstants.ACT_STATUS_04.equals(actActivity.getStatus())){
            return AjaxResult.error(AppConstants.ERROR_CODE_01,"该活动已结束！");
        }
        ActActivityBasics activityBasics = actActivityBasicsService.selectActActivityBasicsByActId(activityId);
        log.info("activityBasics:{}",activityBasics);
        if (DateUtils.dateTime(DateUtils.YYYY_MM_DD,activityBasics.getEndTime()).before(new Date())&&!DateUtils.dateTime(new Date()).equals(activityBasics.getEndTime())){
            return AjaxResult.error(AppConstants.ERROR_CODE_01,"该活动已结束/活动未开始");
        }

        if (DateUtils.dateTime(DateUtils.YYYY_MM_DD,activityBasics.getStartTime()).after(new Date())&&!DateUtils.dateTime(new Date()).equals(activityBasics.getEndTime())){
            return AjaxResult.error(AppConstants.ERROR_CODE_06,"活动未开始");
        }
        AppActivityWayVo appActivityWayVo = new AppActivityWayVo();
        appActivityWayVo.setActivityId(activityId);
        appActivityWayVo.setUserId(actUserId);
        //判断每人总抽奖次数
        if (AppConstants.LIMIT_YS.equals(actActivityAwardWay.getLotteryTotalLimit())){
            int lotteryTotalMax = actActivityUserService.getDrawCount(appActivityWayVo);

            log.info("lotteryTotalMax:{}",lotteryTotalMax);
            if (lotteryTotalMax >= Integer.parseInt(actActivityAwardWay.getLotteryTotalMax())){
                return AjaxResult.error(AppConstants.ERROR_CODE_02,"您的抽奖次数已达上限！");
            }
        }
        //判断每人每日抽奖次数
        appActivityWayVo.setCreateTime(DateUtils.getDate());
        int lotteryDayNum = actActivityUserService.getDrawCount(appActivityWayVo);
        log.info("lotteryDayNum:{}",lotteryDayNum);
        if (lotteryDayNum >= Integer.parseInt(actActivityAwardWay.getLotteryDayNum())){
            return AjaxResult.error(AppConstants.ERROR_CODE_03,"您今日的抽奖次数已达上限！");
        }
        lock.lock();
        ActActivityUserAward actActivityUserAward = new ActActivityUserAward();
        try {
            //中奖及奖品校验
            boolean result = actDrawService.judgeDraw(activityId,actUserId,actActivityAwardWay);
            log.info("result:{}",result);
            ActActivityUser actActivityUser = new ActActivityUser();
            actActivityUser.setActivityId(activityId);
            actActivityUser.setUserId(actUserId);
            actActivityUser.setCreateTime(new Date());
            if (result){
                //获得抽奖的id    未中奖默认传-1;
                actActivityUserAward = actDrawService.findDrawTypeInfo(actUserId, activityId);
                log.info("actActivityUserAward:{}",actActivityUserAward);
                if (actActivityUserAward == null){
                    //参与用户状态：1中奖2未中奖
                    actActivityUser.setStatus("2");
                } else {
                    actActivityUser.setStatus("1");
                }
            } else {
                //参与用户状态未中奖
                actActivityUser.setStatus("2");
            }
            actActivityUserService.insertActActivityUser(actActivityUser);
        } finally {
            // 释放锁
            lock.unlock();
        }
        int surplusNum = actActivityUserService.getSurplusNum(actUserId,activityId, DateUtils.getDate());
        log.info("surplusNum:{}",surplusNum);
        if (AppConstants.LIMIT_YS.equals(actActivityAwardWay.getLotteryTotalLimit())){
            int resultNum = actActivityUserService.getTotalSurplusNum(actUserId, activityId);
            log.info("resultNum:{}",resultNum);
            if ( surplusNum > resultNum){
                surplusNum = resultNum;
            }
        }

        boolean prizeAddress=false;
        ActUser actUser = actUserService.selectActUserById(actUserId);
        String addressDetail = actUser.getAddressDetail();
        if (!StringUtils.isBlank(addressDetail)){
            prizeAddress=true;
        }
        Map<String,Object> map = new HashMap<>();
        map.put("drawInfoId",actActivityUserAward.getPrizeId()!=null?actActivityUserAward.getPrizeId():"-1");
        map.put("recordId",actActivityUserAward.getId());
        map.put("surplusNum",surplusNum);
        map.put("prizeAddress",prizeAddress);
        return AjaxResult.success(map);
    }

    public static void main(String[] args) {
        boolean before = DateUtils.dateTime(DateUtils.YYYY_MM_DD, "2023-05-10").before(new Date());
        System.out.println(before);
    }
}
